<template>
  <div class="awsCenter">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" style="width: 100%">
      <el-tab-pane label="分段尺寸信息" name="size">
        <div style="border: black 0px solid;width: 100%;height: 550px;display: flex;
flex-direction: column;
align-items: center;">
            <!--    按钮栏    -->
            <div class="awsCenter" style="width: 100%;height: 40px;border: black 0px solid">
              <el-input style="width: 150px;margin-right: 10px" placeholder="船型" v-model="sizeSelectForm.ship_type"></el-input>
              <el-input style="width: 150px;margin-right: 10px" placeholder="周期" v-model="sizeSelectForm.station_cycle"></el-input>

              <el-button @click="getSize" style="width: 80px;margin-left: 10px" type="primary" plain>查询</el-button>
              <el-button @click="sizeRefresh" style="margin-left: 10px" type="primary" circle><el-icon><refresh /></el-icon></el-button>


              <div style="margin-left: auto">
                <el-button style="width: 80px;" type="primary" @click="showSize=true;sizeFlag='new';sizeTitle='新增尺寸信息';cleanSizeForm();">新增</el-button>
                <el-button style="margin-left: 0px" @click="confDelete">批量删除</el-button>
                <ImportExcelButton v-if="activeName==='size'||activeName==='produce'" style="margin-left: 20px" :fields="importFields" @import-data="handleImportData" />
              </div>

            </div>

          <!--   表格    -->
          <el-table :data="shipSegmentsList" stripe style="width: 100%;margin-top: 20px" @selection-change="selectClient">
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column prop="ship_number" label="船号" width="150" />
            <el-table-column prop="ship_type" label="船型" width="100" />
            <el-table-column prop="segment_number" label="分段号" width="100" />
            <el-table-column prop="station_cycle" label="胎位周期" width="100px"/>
            <el-table-column prop="segment_length" label="分段长（m）" width="150px"/>
            <el-table-column prop="segment_width" label="分段宽（m）" width="150px"/>
            <el-table-column prop="segment_height" label="分段高（m）" width="150px"/>
            <el-table-column prop="segment_weight" label="分段重量（t）" width="150px"/>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="primary" plain :icon="Edit" circle @click="showSize=true;sizeFlag='edit';sizeTitle='修改尺寸信息';showSizeData(row)" />
                <el-button type="danger" plain :icon="Delete" circle @click="handleClientDelete(row)" />
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页条 -->
          <div  class="demo-pagination-block">
            <el-pagination
              style="margin-top: 20px"
              v-model:current-page="currentPage"
              :page-size="8"
              :size="size"
              :disabled="disabled"
              :background="background"
              layout="total, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>

        </div>
      </el-tab-pane>
      <el-tab-pane label="分段生产信息" name="produce">
        <div style="border: black 0px solid;width: 100%;height: 550px;display: flex;
flex-direction: column;
align-items: center;">
          <!--    按钮栏    -->
          <div class="awsCenter" style="width: 100%;height: 40px;border: black 0px solid">
            <el-input style="width: 200px;margin-right: 10px" placeholder="船号" v-model="produceSelectForm.ship_number"></el-input>
            <div class="demo-date-picker" style="margin-left: 10px">
              <div class="block">
                <el-date-picker
                  v-model="produceSelectForm.dateTime"
                  type="daterange"
                  range-separator="~"
                  start-placeholder="中日程计划开工时间"
                  end-placeholder="中日程计划完工时间"
                />
              </div>
            </div>
            <el-button @click="getProduce(1)" style="width: 80px;margin-left: 10px" type="primary" plain>查询</el-button>
            <el-button @click="produceRefresh" style="margin-left: 10px" type="primary" circle><el-icon><refresh /></el-icon></el-button>


            <div style="margin-left: auto">
              <ImportExcelButton v-if="activeName==='size'||activeName==='produce'" style="margin-left: 20px" :fields="importFields" @import-data="handleImportData" />
            </div>
          </div>


          <!--   表格    -->
          <el-table :data="produceList" stripe style="width: 100%;margin-top: 20px" @selection-change="selectClient">
<!--            <el-table-column type="selection" :selectable="selectable" width="55" />-->
            <el-table-column prop="ship_number" label="船号" width="150" />
            <el-table-column prop="ship_type" label="船型" width="100" />
            <el-table-column prop="segment_number" label="分段号" width="100" />
            <el-table-column
              prop="mid_schedule_start"
              label="中日程计划开工时间"
              width="150px"
              :formatter="(row, column, cellValue) => formatDate(cellValue)"
            />
            <el-table-column
              prop="mid_schedule_end"
              label="中日程计划完工时间"
              width="150px"
              :formatter="(row, column, cellValue) => formatDate(cellValue)"
            />
            <el-table-column
              prop="earliest_start"
              label="最早开工时间"
              width="150px"
              :formatter="(row, column, cellValue) => formatDate(cellValue)"
            />
            <el-table-column
              prop="latest_start"
              label="最晚开工时间"
              width="150px"
              :formatter="(row, column, cellValue) => formatDate(cellValue)"
            />
            <el-table-column
              prop="latest_end"
              label="最晚完工时间"
              width="150px"
              :formatter="(row, column, cellValue) => formatDate(cellValue)"
            />
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="primary" plain :icon="Edit" circle @click="showProduce=true;updateProduce(row);" />
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页条 -->
          <div  class="demo-pagination-block">
            <el-pagination
              style="margin-top: 20px"
              v-model:current-page="currentPage"
              :page-size="8"
              :size="size"
              :disabled="disabled"
              :background="background"
              layout="total, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>

        </div>
      </el-tab-pane>
      <el-tab-pane label="分段组合信息" name="couple">
        <CompareTable v-if="activeName==='couple'"></CompareTable>
      </el-tab-pane>

      <el-tab-pane label="胎位信息" name="fetal">
         <FetalTable v-if="activeName==='fetal'"></FetalTable>
      </el-tab-pane>
      <el-tab-pane label="已有分段信息" name="scheduling">
        <SchedulingTable v-if="activeName==='scheduling'"></SchedulingTable>
      </el-tab-pane>
    </el-tabs>


    <el-dialog v-model="confDialog" :close-on-click-modal="false" title="是否确认删除 ?" width="400" center>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="margin-right: 10px" @click="confDialog = false">取 消</el-button>
          <el-button style="margin-right: 20px" type="primary" @click="confDeleteDialog">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog
      v-model="showSize"
      :title="sizeTitle"
      width="600"
      align-center
      style="height: 500px; /* 固定高度 */
          "
      draggable
      :close-on-click-modal="false"
    >

      <div style="padding: 20px;height: 400px">
        <el-form :model="shipSegmentsForm" label-position="top" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <!-- 左侧表单项 -->
            <el-col :span="12">
              <el-form-item prop="ship_number" label="船号">
                <el-input style="width: 200px;" v-model="shipSegmentsForm.ship_number"></el-input>
              </el-form-item>
              <el-form-item prop="ship_type" label="船型">
                <el-input style="width: 200px;" v-model="shipSegmentsForm.ship_type"></el-input>
              </el-form-item>
              <el-form-item prop="station_cycle" label="胎位周期">
                <el-input-number v-model="shipSegmentsForm.station_cycle" :min="1"></el-input-number>
              </el-form-item>
              <el-form-item prop="segment_number" label="分段号">
                <el-input style="width: 200px;" v-model="shipSegmentsForm.segment_number"></el-input>
              </el-form-item>
            </el-col>

            <!-- 右侧表单项 -->
            <el-col :span="12">
              <el-form-item prop="segment_length" label="分段长（m）">
                <el-input-number v-model="shipSegmentsForm.segment_length" :precision="2" :step="0.1" :min="0"></el-input-number>
              </el-form-item>
              <el-form-item prop="segment_width" label="分段宽（m）">
                <el-input-number v-model="shipSegmentsForm.segment_width" :precision="2" :step="0.1" :min="0"></el-input-number>
              </el-form-item>
              <el-form-item prop="segment_height" label="分段高（m）">
                <el-input-number v-model="shipSegmentsForm.segment_height" :precision="2" :step="0.1" :min="0"></el-input-number>
              </el-form-item>
              <el-form-item prop="segment_weight" label="分段重量（t）">
                <el-input-number v-model="shipSegmentsForm.segment_weight" :precision="2" :step="0.1" :min="0"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <template #footer>
        <div style="margin-top: -20px">
          <el-button @click="showSize = false">取 消</el-button>
          <el-button type="primary" @click="sizeSaveOrUpdate">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog
      v-model="showProduce"
      title="维护生产时间"
      width="600"
      align-center
      style="height: 500px; /* 固定高度 */
          "
      draggable
      :close-on-click-modal="false"
    >

      <div style="padding: 20px;height: 400px">
        <el-form :model="segmentScheduleForm" label-position="top" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <!-- 左侧表单项 -->
            <el-col :span="12">
              <el-form-item prop="ship_number" label="船号">
                <el-input :disabled="true" style="width: 200px;" v-model="segmentScheduleForm.ship_number"></el-input>
              </el-form-item>
              <el-form-item prop="ship_type" label="船型">
                <el-input :disabled="true" style="width: 200px;" v-model="segmentScheduleForm.ship_type"></el-input>
              </el-form-item>
              <el-form-item prop="segment_number" label="分段号">
                <el-input :disabled="true" style="width: 200px;" v-model="segmentScheduleForm.segment_number"></el-input>
              </el-form-item>
              <el-form-item prop="latest_start" label="最晚开工时间">
                <el-date-picker
                  v-model="segmentScheduleForm.latest_start"
                  type="date"
                  placeholder="请选择"
                  size="default"
                />
              </el-form-item>
            </el-col>

            <!-- 右侧表单项 -->
            <el-col :span="12">
              <el-form-item prop="mid_schedule_start" label="中日程计划开工时间">
                <el-date-picker
                  v-model="segmentScheduleForm.mid_schedule_start"
                  type="date"
                  placeholder="请选择"
                  size="default"
                />
              </el-form-item>
              <el-form-item prop="mid_schedule_end" label="中日程计划完工时间">
                <el-date-picker
                  v-model="segmentScheduleForm.mid_schedule_end"
                  type="date"
                  placeholder="请选择"
                  size="default"
                />
              </el-form-item>
              <el-form-item prop="earliest_start" label="最早开工时间">
                <el-date-picker
                  v-model="segmentScheduleForm.earliest_start"
                  type="date"
                  placeholder="请选择"
                  size="default"
                />
              </el-form-item>

              <el-form-item prop="latest_end" label="最晚完工时间">
                <el-date-picker
                  v-model="segmentScheduleForm.latest_end"
                  type="date"
                  placeholder="请选择"
                  size="default"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <template #footer>
        <div style="margin-top: -20px">
          <el-button @click="showProduce = false">取 消</el-button>
          <el-button type="primary" @click="produceSaveOrUpdate">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>


  </div>

</template>
<script lang="ts" setup>
import {getUserClientService,userRegisterService,deleteClientService,updateClientService} from '@/api/user.js'
import {ElMessage, ElMessageBox, UploadFile} from "element-plus";
const confDialog = ref(false)
import moment from 'moment';
import type { ComponentSize } from 'element-plus'
const currentPage = ref(1)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
import { Refresh } from '@element-plus/icons-vue';

import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
import {upload} from '@/api/upload.js'

const imageUrl = ref('')

const getStatusType=((status)=>{
  if (status=='未申请'){
    return 'info'
  }else if (status=='已申请'){
    return 'warning'
  }else if (status=='已入驻'){
    return 'success'
  }else {
    return 'error'
  }
})
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过2MB')
    return false
  }
  return true
}




const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = async (val: number) => {
  if (activeName.value==='size'){
    await getSize(val)
  }else if (activeName.value==='produce'){
    await getProduce(val)
  }
}
import {
  Delete,
  Edit,
} from '@element-plus/icons-vue'
import {onMounted, ref, watch} from 'vue'
import type { TabsPaneContext } from 'element-plus'
const dateTime = ref('')
const realName=ref('')
const activeName = ref('size')

import {useUserStore} from "@/stores/user/user.js";
import { useRouter } from 'vue-router'
import { getByUserIdService } from '@/api/counselor'
const userStore=useUserStore()
const router = useRouter();
const importFields = ref<string[]>([])
onMounted(async ()=>{
  //分段尺寸信息查询
  await getSize(1)

  importFields.value= Object.keys(shipSegmentsForm.value).slice(1)

})
const gender = ref('')

const options = [
  {
    value: '男',
    label: '男',
  },
  {
    value: '女',
    label: '女',
  }
]

const userType=ref("client")
const dialogTitle=ref('')

//修改选择角色
const buttonDisabled=ref(false)
const handleClick = async (tab: TabsPaneContext, event: Event) => {
  activeName.value=tab.props.name
  selected.value=[]
  if(activeName.value==='size'){
    await getSize(1)
    importFields.value= Object.keys(shipSegmentsForm.value).slice(1)
  }else if (activeName.value==='produce'){
    await getProduce(1)
    importFields.value= Object.keys(segmentScheduleForm.value).slice(2)
  }

}



const tableData = ref([])

const selectData=ref({
  current:currentPage.value,
  pageSize:8,
  realname:'',
  gender:'',
  beginDate:'',
  endDate:''

})
//查询
const total=ref(0)
const getClient=(async ()=>{

  selectData.value={
    current:currentPage.value,
    pageSize:8,
    realname:realName.value,
    gender:gender.value,
    beginDate:dateTime.value ? moment(dateTime.value[0]).format('YYYY-MM-DD') : null,
    endDate:dateTime.value ? moment(dateTime.value[1]).format('YYYY-MM-DD') : null
  }
  console.log(selectData.value)
  const body = {
    userDto: selectData.value,
    type: userType.value  // 将需要传递的 type 参数赋值给对应的键
  };

  const res=await getUserClientService(body)
  if (res.code===200){
    tableData.value=res.data.data
    tableData.value.forEach(item => {
      if (item.username===userStore.user.username){
        item.disabled = true
      }else {
        item.disabled = false; // 向每个对象添加 disabled 属性并设置初始值

      }
      if (item.status==0){
        item.status='未申请'
      }else if (item.status==2){
        item.status='已申请'
      }else if (item.status==1){
        item.status='已入驻'
      }else {
        item.status='已拒绝'
      }

    });
    dateFormat()
    total.value=res.data.total
    console.log(tableData.value)
  }
})

const cleanSelectData=(()=>{
  selectData.value={
    current:currentPage.value,
    pageSize:8,
    realname:'',
    gender:'',
    beginDate:'',
    endDate:''
  }
  realName.value=''
  gender.value=''
  dateTime.value=''
})

const dateFormat=(()=>{
  for (let i = 0; i < tableData.value.length; i++) {
    if (tableData.value[i].birthday){
      tableData.value[i].birthday=moment(tableData.value[i].birthday).format('YYYY-MM-DD')
    }
  }
})

const selectable = (row, index) => {
  // 在这里可以设置某些条件下的行是否可选
  if (row.username===userStore.user.username){
    return false;
  }
  return true;
};

const saveClientClass=ref('accountInfo')
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  confPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
  ]
};

//新增///////////////////
const showSaveClient=ref(false)
const clientForm=ref({
  username: '',
  password:'',
  nickname: '',
  realname: '',
  avatar:'',
  gender: '',
  email: '',
  phone: '',
  birthday: null,
  address: '',
  usertype:''
})
const confPassword=ref('')

//清空来访者表单数据
const cleanClientForm=(()=>{
  clientForm.value={
    username: '',
    password:'',
    nickname: '',
    realname: '',
    avatar:'',
    gender: '',
    email: '',
    phone: '',
    birthday: null,
    address: '',
    usertype:''
  }
  confPassword.value=''
  imageUrl.value=''
})


//设置修改或新增的标识
const sou=ref(false)//false是新增，true是修改
const saveClient=(async ()=>{
  showSaveClient.value=true
  if (!confPassword.value&&!clientForm.value.password&&!clientForm.value.username){
    ElMessage.warning("请填写完整")
  }else if (confPassword.value!==clientForm.value.password){
    ElMessage.warning("两次密码输入不一致")
  }else {
    clientForm.value.usertype=userType.value
    console.log(clientForm.value)
    let res=await userRegisterService(clientForm.value)
    if (res.code===200){
      await getClient()
      ElMessage.success("新增成功")
      showSaveClient.value=false
      cleanClientForm()
    }else {
      ElMessage.warning(res.errMsg)
    }
  }
})


//给选中的数据赋值
const handleUpdate=((row)=>{
  console.log(row)
  clientForm.value=conFix(row)
  imageUrl.value=row.avatar

  confPassword.value=row.password
  console.log(clientForm.value)
})
const conFix=((row)=>{
  //审核状态:  0是未申请 1是已通过 2是已申请 3是已拒绝
  if (row.usertype=="counselor"){
    if (row.status == "未申请") {
      row.status = "0";
    } else if (row.status == "已入驻") {
      row.status = "1";
    } else if (row.status == "已通过") {
      row.status = "2";
    }else {
      row.status = "3";
    }
  }else {
    row.status="0"
  }
  return row;
})
const handleClientEdit=(async ()=>{

  const res=await updateClientService(clientForm.value)
  if (res.code===200){
    await getClient()
    ElMessage.success(res.message)
    showSaveClient.value=false
    cleanClientForm()
  }else {
    ElMessage.warning(res.errMsg)
  }

})

const saveOrUpdate=(()=>{
  if (sou.value){

    handleClientEdit()
  }else{
    saveClient()
  }
})



const selected=ref([])
function selectClient(selectedRows) {
  console.log(selectedRows)
  selected.value=selectedRows
}

const deleteClientRows=(async ()=>{
  console.log(selected.value)
  if (selected.value.length===0){
    ElMessage.warning("请先选择数据")
  }else {

    let res=await deleteClientService(selected.value)
    console.log(res)
    if (res.code===200){
      ElMessage.success(res.message)
      await getClient()
      selected.value=[]
    }else {
      ElMessage.warning(res.errMsg)
    }
  }

})

const confDelete=(()=>{
  if (selected.value.length===0){
    ElMessage.warning("请先选择数据")
  }else {
    ElMessageBox.confirm(
      '您确定要删除吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {

      // 执行删除操作
      if (activeName.value==='size'){
        deleteSize()
      }

    }).catch((err) => {
      console.log(err)
    });
  }
})

//单个删除
const handleClientDelete=(async (row)=>{
  selected.value.push(row)
  console.log(row)
  ElMessageBox.confirm(
    '您确定要删除吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {

    // 执行删除操作
    if (activeName.value==='size'){
      deleteSize()
    }

  }).catch((err) => {
    console.log(err)
  });
  //confDialog.value=true
})

//公用 ：删除确认框
const confDeleteDialog=(()=>{

  confDialog.value = false
})









//咨询师审核
const examineImageUrl=ref('')
const examine=(async (row)=>{
  //赋值基本信息
  userForm.value={...row}
  examineImageUrl.value=row.avatar
  console.log(examineImageUrl.value)
  //赋值咨询师信息
  const conRes=await getByUserIdService(row.userid)
  if (conRes.code===200){
    counselorForm.value={...conRes.data}
    //赋值工作时间
    timeRows.value=conRes.data.counselorscheduleList
  }

  showExamine.value=true
  if (timeRows.value.length!=0){
    timeRows.value.forEach(item=>{
      item.endtime=item.endtime.toString().split(' ')[3]
      item.starttime=item.starttime.toString().split(' ')[3]
    })
  }

})

const showExamine=ref(false)
const isDisabled=ref(true)
const examineClass=ref('1')

//表单数据
const counselorForm=ref({
  username:'',
  specialty:'',
  bio:'',
  status:'1',
  counselorscheduleList:[]
})

const userForm=ref({
  nickname:'',
  realname:'',
  gender:'',
  avatar:'',
  email:'',
  phone:'',
  birthday:'',
  address:'',
  status:'2'
})

const changeExamine=(()=>{

})

const cleanExamine=(()=>{
  counselorForm.value= {
    username: '',
    specialty: '',
    bio: '',
    status: '1',
    counselorscheduleList: []
  }
  userForm.value={
    nickname:'',
    realname:'',
    gender:'',
    avatar:'',
    email:'',
    phone:'',
    birthday:'',
    address:'',
    status:'2'
  }
  timeRows.value=[]
  examineImageUrl.value=''
})

const timeRows = ref([
]);

const addRow = () => {
  timeRows.value.push({
    room: '',
    weekend: '',
    starttime: '',
    endtime:''
  });
};

const deleteRow = (index: number) => {
  timeRows.value.splice(index, 1);
};


const drawer=ref(false)

const filedForm=ref({
   username:'',
   approvalresult:'',
   approvalnote:'',
   approver:'',
   updatedat:''
})

const cleanFiledForm=(()=>{
  filedForm.value={
    username:'',
    approvalresult:'',
    approvalnote:'',
    approver:'',
    updatedat:''
  }
})

//弹出审批单子
const filed=((username)=>{
  drawer.value=true

  filedForm.value.approver=userStore.user.nickname
  filedForm.value.updatedat=new Date()
  filedForm.value.username=username
  console.log(filedForm.value)
})


import {approvalService} from '@/api/filed.js'
//提交审批
const approval=(async ()=>{
  filedForm.value.updatedat=new Date()
  if (filedForm.value.approvalresult){
    console.log(filedForm.value)
    const res=await approvalService(filedForm.value)
    if (res.code===200){
      ElMessage.success(res.message)

      //刷新视图
      drawer.value=false
      showExamine.value=false
      await getClient()
    }else {
      ElMessage.warning(res.errMsg)
    }

  }else {
    ElMessage.warning("请填写审批结果")
  }
})

import {
  addSegmentService,
  deleteSegmentsService,
  getSegmentsService, importSegmentsService,
  updateSegmentsService
} from '@/api/ship_segments.js'
import {
  addProduceService,
  getProduceService,
  importSegmentSchedulesService,
  updateSchedulesService
} from '@/api/segment_schedule.js'
import FetalTable from "@/components/FetalTable.vue";
import SchedulingTable from "@/components/SchedulingTable.vue";
import {batchAddBayAssignedSegmentsService} from "@/api/bay_assignment";
import ImportExcelButton from "@/components/ImportExcelButton.vue";
import CompareTable from "@/components/CompareTable.vue";

//分段尺寸信息
const showSize=ref(false)
const sizeFlag=ref('')
const sizeTitle=ref('')

const shipSegmentsForm = ref({
  ship_segments_id: '',
  ship_number: '',
  ship_type: '',
  segment_number: '',
  station_cycle: null,   // 改成 null
  segment_length: null,  // 同上
  segment_width: null,
  segment_height: null,
  segment_weight: null
});



const cleanSizeForm=(()=>{
  shipSegmentsForm.value={
    ship_segments_id:'',
    ship_number:'',
    ship_type:'',
    segment_number:'',
    station_cycle: null,   // 改成 null
    segment_length: null,  // 同上
    segment_width: null,
    segment_height: null,
    segment_weight: null
  }
})

const sizeSaveOrUpdate=(async ()=>{
  if (sizeFlag.value==='new'){
    //新增数据
    console.log(shipSegmentsForm.value)
    if (shipSegmentsForm.value.ship_type&&shipSegmentsForm.value.ship_number&&shipSegmentsForm.value.segment_number&&shipSegmentsForm.value.segment_length&&shipSegmentsForm.value.segment_width&&shipSegmentsForm.value.segment_height&&shipSegmentsForm.value.segment_weight&&shipSegmentsForm.value.station_cycle!==null){
      let res=await addSegmentService(shipSegmentsForm.value)
      if (res.code===200){
        ElMessage.success("新增成功")
        showSize.value=false
        await getSize(1)
      }
    }else {
      ElMessage.warning("请填写完整")
    }
  }else{
    //修改数据
    console.log(shipSegmentsForm.value)
    let res=await updateSegmentsService(shipSegmentsForm.value.ship_segments_id,shipSegmentsForm.value)
    if (res.code===200){
      ElMessage.success("修改成功")
      showSize.value=false
      await getSize(1)
    }
  }
})

const showSizeData=((row)=>{
  shipSegmentsForm.value={...row}
})

const sizeSelectForm=ref({
  current:'',
  pageSize:8,
  ship_type:'',
  station_cycle:''
})
const shipSegmentsList=ref([])
const getSize=async (val)=>{
  sizeSelectForm.value.current=val
  let res=await getSegmentsService(sizeSelectForm.value)
  if (res.code===200){
    shipSegmentsList.value=res.data.list
    total.value=res.data.total
  }
}

const sizeRefresh=(()=>{
  sizeSelectForm.value.ship_type=''
  sizeSelectForm.value.station_cycle=''
  getSize(1)
})

const deleteSize=(async ()=>{
  await deleteSegmentsService(selected.value).then(res=>{
    if (res.code===200){
      ElMessage.success('删除成功')
      getSize(1)
    }
  })
  selected.value=[]
})


function formatDate(date) {
  if (!date) return '';

  const d = new Date(date);
  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, '0');
  const day = d.getDate().toString().padStart(2, '0');

  return `${year}-${month}-${day}`;
}

const produceSelectForm=ref({
  current:'',
  pageSize:8,
  ship_number:'',
  mid_schedule_start:'',
  mid_schedule_end:'',
  dateTime:null
})
watch(() => produceSelectForm.value.dateTime, (newVal, oldVal) => {
  console.log(newVal); // 输出新的dateTime值
  if (newVal && newVal.length === 2){
    produceSelectForm.value.mid_schedule_start = newVal[0];
    produceSelectForm.value.mid_schedule_end = newVal[1];
  }
}, { deep: true }); // 使用 deep 选项监听对象内部的变化

const produceList=ref([])
const getProduce=(async (val) => {
  produceSelectForm.value.current = val
  let res = await getProduceService(produceSelectForm.value)
  console.log(res)
  if (res.code === 200) {
    produceList.value = res.data.list
    total.value = res.data.total
  }
})


const produceRefresh=(()=>{
  produceSelectForm.value.ship_number=''
  produceSelectForm.value.mid_schedule_start=''
  produceSelectForm.value.mid_schedule_end=''
  produceSelectForm.value.dateTime=null
  getProduce(1)
})

const showProduce=ref(false)
const segmentScheduleForm=ref({
  segment_schedule_id: '',
  ship_segments_id: '',
  ship_number:'',
  ship_type:'',
  segment_number: '',
  mid_schedule_start: null,
  mid_schedule_end: null,
  earliest_start: null,
  latest_start: null,
  latest_end: null
})
const updateProduce=((row)=>{
  segmentScheduleForm.value={...row}
})

const produceSaveOrUpdate=(()=>{
  let form={
    segment_schedule_id: segmentScheduleForm.value.segment_schedule_id,
    ship_segments_id: segmentScheduleForm.value.ship_segments_id,
    segment_number: segmentScheduleForm.value.segment_number,
    mid_schedule_start: segmentScheduleForm.value.mid_schedule_start,
    mid_schedule_end: segmentScheduleForm.value.mid_schedule_end,
    earliest_start: segmentScheduleForm.value.earliest_start,
    latest_start: segmentScheduleForm.value.latest_start,
    latest_end: segmentScheduleForm.value.latest_end
  }
  //修改
  if (segmentScheduleForm.value.segment_schedule_id){
    console.log(form)
    updateSchedulesService(form).then(res=>{
      if (res.code===200){
        ElMessage.success("修改成功")
        showProduce.value=false
        getProduce(1)
      }
    })
  }else {
    //新增
    console.log(form)
    if (form.mid_schedule_start&&form.mid_schedule_end&&form.earliest_start&&form.latest_start&&form.latest_end){
      addProduceService(form).then(res=>{
        if (res.code===200){
          ElMessage.success("新增成功")
          showProduce.value=false
          getProduce(1)
        }
      })
    }else{
      ElMessage.warning("请填写完整")
    }
  }
})


const importedData = ref<any[]>([])

const handleImportData = async (data: any[]) => {
  console.log('导入的数据:', data)

  if(activeName.value==='size'){
    importedData.value = data
    const res = await importSegmentsService(importedData.value)
    if (res.code === 200) {
      ElMessage.success(res.message)
      await getSize(1)
    }
  }else if(activeName.value==='produce'){
    importedData.value = data
    const res = await importSegmentSchedulesService(importedData.value)
    if (res.code === 200) {
      ElMessage.success(res.message)
      await getProduce(1)
    }
  }

}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
}
.demo-date-picker {
  display: flex;
  padding: 0;
  flex-wrap: wrap;
}
.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 0;
}
.demo-date-picker .block:last-child {
  border-right: none;
}
.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.awsCenter{
  display: flex;
  align-items: center;
}
</style>
